package com.travelDevelop.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.travelDevelop.commons.bean.SysFile;
import com.travelDevelop.commons.bean.User;
import com.travelDevelop.commons.util.ForFile;
import com.travelDevelop.commons.util.ToolString;
import com.travelDevelop.commons.util.WebConst;
import com.travelDevelop.dao.FileMapper;

import jxl.read.biff.BiffException;

@Controller
@RequestMapping("/sysfile")
public class SysFileController {

	@Autowired
	FileMapper fileMapper;

	private static final String DIRECTORY = "D:/travelDevelop";
	 
	 private static Logger log = LogManager.getLogger(SysFileController.class);

	@ResponseBody
	@RequestMapping("/uploadExcel")
	public Map<String, String> uploadFile(HttpServletRequest request,HttpServletResponse response,@RequestParam("files") List<MultipartFile> files) throws IOException, BiffException {
		/*
		 * for (MultipartFile file : files) { if (!file.isEmpty()) { // 获取文件名 String
		 * fileName = file.getOriginalFilename();
		 * System.out.println("Uploaded file name: " + fileName); } }
		 */
		HttpSession session = request.getSession();
		SysFile file = new SysFile();

		file.setUploadUser((String)session.getAttribute(WebConst.SESSION_LOGIN_USER_ID));
		file.setUploadTime(LocalDateTime.now());
		file.setUrl(DIRECTORY);

			try {
				ForFile forFile = new ForFile();
				String ctxPath=DIRECTORY;
				String[] fileInfor= forFile.uploadDevelopFile(request, response, ctxPath);
				String fileId = fileInfor[0];

				file.setFileName(fileInfor[1]);
				file.setInsysName(fileInfor[0]);
				fileMapper.insertExcel(file);

				Map<String, String> responseMap = new HashMap<>();
		        responseMap.put("filename", fileId);
				return responseMap;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
	}
	
	
	@ResponseBody
	@RequestMapping("/uploadImg")
	public Map<String, String> uploadImg(HttpServletRequest request,HttpServletResponse response,@RequestParam("files") List<MultipartFile> files) throws IOException, BiffException {
		/*
		 * for (MultipartFile file : files) { if (!file.isEmpty()) { // 获取文件名 String
		 * fileName = file.getOriginalFilename();
		 * System.out.println("Uploaded file name: " + fileName); } }
		 */
		HttpSession session = request.getSession();
		SysFile file = new SysFile();

		file.setUploadUser((String)session.getAttribute(WebConst.SESSION_LOGIN_USER_ID));
		file.setUploadTime(LocalDateTime.now());
		file.setUrl(DIRECTORY);

			try {
				ForFile forFile = new ForFile();
				String ctxPath=DIRECTORY;
				String[] fileInfor= forFile.uploadDevelopFile(request, response, ctxPath);
				String fileId = fileInfor[0];

				file.setFileName(fileInfor[1]);
				file.setInsysName(fileInfor[0]);
				fileMapper.insertImg(file);

				Map<String, String> responseMap = new HashMap<>();
		        responseMap.put("filename", fileId);
				return responseMap;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
	}

	@RequestMapping("/download")
	public void download(HttpServletRequest request,HttpServletResponse response) throws IOException{
		SysFile sysfile = null;
		String fileName = null;
		String imgfile =null;
		if (!ToolString.isNull(request.getParameter("fileName"))) { // 类型
			/* bean.setMeeting_type(request.getParameter("flag")); */
			fileName=request.getParameter("fileName");
		}else if(!ToolString.isNull(request.getParameter("imgfile"))) {
			fileName=request.getParameter("imgfile");
			sysfile = new SysFile();
			sysfile.setId(request.getParameter("id"));
			sysfile=fileMapper.selectImgFile(sysfile).get(0);
			fileName=sysfile.getInsysName();
		}else if(!ToolString.isNull(request.getParameter("id"))) {
			sysfile = new SysFile();
			sysfile.setId(request.getParameter("id"));
			sysfile=fileMapper.selectOrderFile(sysfile).get(0);
			fileName=sysfile.getInsysName();
		}

        if (fileName == null || fileName.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "File name is missing");
            return;
        }

        File file = new File(DIRECTORY,fileName);
        if (!file.exists() || !file.isFile()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }

        ServletOutputStream outputStream = null;
		byte[] return_arraybyte = null;
		InputStream ins = null;
		ByteArrayOutputStream byteOut = null;
		try {
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			fileType = fileType.toUpperCase();
			// 设置文件MIME类型
			response.setContentType("multipart/form-data");
			// 设置Content-Disposition
			if(sysfile != null) {
				fileName = sysfile.getFileName();
			}
			String headerValue = String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "UTF-8"));
			response.setHeader("Content-Disposition", headerValue);

			outputStream = response.getOutputStream();
			ins = new FileInputStream(file);
			byteOut = new ByteArrayOutputStream();
			byte[] buf = new byte[204800];
			int bufsize = 0;

			while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {
				byteOut.write(buf, 0, bufsize);
			}
			return_arraybyte = byteOut.toByteArray();
			byteOut.close();
			ins.close();
			outputStream.write(return_arraybyte);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			log.error(e);
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
			if (byteOut != null)
				byteOut.close();
			if (ins != null)
				ins.close();
		}

		return ;
	}



}
